package com.lingkang.sales.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.lingkang.sales.common.utils.MenuUtil;
import com.lingkang.sales.common.val.HttpCode;
import com.lingkang.sales.data.domain.SecUser;
import com.lingkang.sales.data.dto.ResponseResult;
import com.lingkang.sales.data.entity.SaCompany;
import com.lingkang.sales.data.entity.SaUser;
import com.lingkang.sales.data.mapper.SaCompanyMapper;
import com.lingkang.sales.data.mapper.SaMenuMapper;
import com.lingkang.sales.data.mapper.SaUserMapper;
import com.lingkang.sales.data.vo.MenuVo;
import com.lingkang.sales.service.AuthService;
import com.lingkang.sales.service.UserService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

/**
 * @author linke
 * @date 2020/11/14 20:48
 * @description
 */
@Service
public class UserServiceImpl implements UserService {

  @Autowired
  private SaUserMapper saUserMapper;
  @Autowired
  private AuthService authService;
  @Autowired
  private SaMenuMapper saMenuMapper;
  @Autowired
  private SaCompanyMapper saCompanyMapper;

  @Override
  public SaUser get(String username) {
    return saUserMapper.get(username);
  }

  @Override
  public ResponseResult getMenu() {
    List<String> roles = authService.getUserExistRole();
    List<MenuVo> menu = saMenuMapper.getByRoleName(roles);
    ResponseResult result = new ResponseResult();
    result.setCode(HttpCode.OK);
    if (menu != null) {
      result.setData(JSONObject.toJSON(MenuUtil.listToTree(menu, 0)));
    }
    return result;
  }

  @Override
  public SaCompany getCompany(String comCode) {
    return saCompanyMapper.selectByPrimaryKey(comCode);
  }

  @Override
  public SecUser getLoginUser() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    return (SecUser) authentication.getPrincipal();
  }
}
